package com.onpositive.mediawiki.crawler;

import java.net.MalformedURLException;

import net.sourceforge.jwbf.core.actions.util.ActionException;
import net.sourceforge.jwbf.core.actions.util.ProcessException;
import net.sourceforge.jwbf.mediawiki.bots.MediaWikiBot;

public class GlobalTemplateExtractor {
	
	private final String globalPath = "http://en.wikipedia.org/w/" ;
	StringBuilder sBuilder = new StringBuilder() ;
	MediaWikiBot wBot = null ;
	
	public String loadTemplateDocs( String templateName, String subPath )
	{
		String globalSubPath = createGlobalSubPath(templateName, subPath) ;
		try {
			
			if ( wBot == null )
				wBot = new MediaWikiBot( globalPath ) ;

			String text = wBot.readContent( globalSubPath ).getText() ;
			
			return text ;
			
		} catch (ActionException e) {
			e.printStackTrace();
		} catch (ProcessException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		return null ;
	}
	
	public String createGlobalSubPath( String templateName, String subPath )
	{
		prepareBuilder();
		
		sBuilder.append("Template:" );
		sBuilder.append( templateName.replaceAll(" ", "_") ) ;
		sBuilder.append("/doc") ;
		
		if( subPath.replaceAll("/", "" ).replaceAll( "\\\\", "" ).length() == 0 )
			return sBuilder.toString() ;
		
		if( checkSubpathValidity(subPath) )
			sBuilder.append("/") ;
		
		sBuilder.append( subPath ) ;
		
		return  sBuilder.toString() ;
	}
	
	private boolean checkSubpathValidity(String subPath) {
		if( subPath.length() == 0 )
			return false ;
		
		return !( subPath.startsWith("/") || subPath.startsWith("\\") );
	}
	
	private void prepareBuilder() {
		if( sBuilder == null )
			sBuilder = new StringBuilder() ;
		else
			sBuilder.delete(0, sBuilder.length() ) ;
	}

}
